<template>
  <div
    v-if="formVisibility"
    ref="propertyPanel"
    :style="propertyStyle"
    class="property-panel"
  >
    <el-form
      ref="formRef"
      label-position="left"
      :model="formData"
      label-width="120px"
      size="small"
      :disabled="!editable"
      @submit.native.prevent
    >
      <!-- 开始和结束节点 -->
      <div v-if="startEvent || endEvent">
        <el-form-item label="ID">
          <el-input v-model="formData.id" maxlength="50" />
        </el-form-item>
        <el-form-item v-if="startEvent || endEvent" label="名称">
          <el-input v-model="formData.nodeName" maxlength="64" @blur="nameChange(formData.nodeName)" />
        </el-form-item>
      </div>

      <!-- 网关以及用户任务 -->
      <div
        v-if="exclusiveGateway || userTask || parallelGateway || sequenceFlow"
      >
        <el-form-item label="步骤名称" prop="nodeName" :rules="userTask? formRules.nodeName : []">
          <el-input v-model="formData.nodeName" maxlength="50" @blur="nameChange(formData.nodeName)" />
        </el-form-item>
        <div v-if="showFlowMore">
          <el-form-item label="条件表达式" prop="expression" :rules="formRules.expression">
            <el-input ref="expression" v-model="formData.expression" disabled />
          </el-form-item>
          <el-form-item label-width="0">
            跳转条件
            <span v-if="!formData.conditions.length">未配置任何条件 </span>
            <span v-else>已配置 {{ formData.conditions.length }}个条件 </span>
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="addCondition"
            >添加</el-button>
          </el-form-item>
        </div>
      </div>
      <div v-if="userTask">
        <div v-if="!showUserMore">
          <el-form-item label="节点表单" prop="formId" :rules="formRules.formId">
            <el-select
              v-model="formData.formId"
              clearable
              placeholder="请选择"
              @change="handleChangeFormId"
            >
              <!-- @change="bindFormData(formData.formId)" -->
              <el-option
                v-for="item in fromSystemList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="挂起节点" prop="hangUp">
          <el-switch
            v-model="formData.hangUp"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
        <!-- 当用户2条时，可以将节点转换为会签节点 -->
        <div v-if="showUserMore">
          <el-form-item label="是否会签" prop="sign">
            <el-switch
              v-model="formData.sign"
              :active-value="true"
              :inactive-value="false"
              inactive-color
            />
          </el-form-item>
        </div>
        <!-- 会签 -->
        <div v-if="formData.sign">
          <el-form-item label="分配方式" prop="nodeAssignMode" :rules="isGateway? formRules.nodeAssignMode : []">
            <el-select
              v-model="formData.nodeAssignMode"
              clearable
              placeholder="请选择"
              :disabled="isGateway"
            >
              <el-option
                v-for="item in actionModeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理人类型" prop="candidateMode" :rules="formRules.candidateMode">
            <el-select
              v-model="formData.candidateMode"
              clearable
              placeholder="请选择"
              @change="handleChangeUserType"
            >
              <el-option
                v-for="item in computedPopleList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="formData.candidateMode != 'allUser'" label="候选处理人" prop="signUserArr" :rules="formRules.signUserArr">
            <el-select
              v-model="formData.signUserArr"
              multiple
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in computedPeople"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="formData.candidateMode != 'allUser'" label="是否指定部门" prop="assignDept">
            <el-switch
              v-model="formData.assignDept"
              :active-value="true"
              :inactive-value="false"
              inactive-color
            />
          </el-form-item>
          <el-form-item label="通过要求票数≥" prop="signVal">
            <el-input-number
              v-model="formData.signVal"
              controls-position="right"
              :min="1"
            />
          </el-form-item>
        </div>
        <!-- 非会签节点 -->
        <div v-if="!formData.sign && showUserMore">
          <el-form-item label="节点表单" prop="formId" :rules="formRules.formId">
            <el-select
              v-model="formData.formId"
              clearable
              placeholder="请选择"
              @change="handleChangeFormId"
            >
              <el-option
                v-for="item in fromSystemList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分配方式" prop="nodeAssignMode">
            <el-select
              v-model="formData.nodeAssignMode"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in actionModeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理人类型" prop="candidateMode" :rules="formRules.candidateMode">
            <el-select
              v-model="formData.candidateMode"
              clearable
              placeholder="请选择"
              @change="handleChangeUserType(formData.candidateMode)"
            >
              <el-option
                v-for="item in computedPopleList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="formData.candidateMode != 'allUser'"
            label="候选处理人"
            prop="candidateUserArr"
            :rules="formRules.candidateUserArr"
          >
            <el-select
              v-model="formData.candidateUserArr"
              multiple
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in computedPeople"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="formData.candidateMode != 'allUser'" label="是否指定部门" prop="assignDept">
            <el-switch
              v-model="formData.assignDept"
              :active-value="true"
              :inactive-value="false"
              inactive-color
            />
          </el-form-item>
          <!-- <el-form-item
            v-if="formData.nodeAssignMode === 'autoAssign'"
            label="默认处理人"
            prop="defaultUser"
          >
            <el-select
              v-model="formData.defaultUser"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in computedPeople"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="允许驳回" prop="isReject">
            <el-checkbox
              v-model="formData.isReject"
              :true-label="1"
              :false-label="0"
            />
          </el-form-item>
          <el-form-item
            v-if="~~formData.isReject"
            label="允许驳回步骤"
            prop="rejectNodeIdArr"
            :rules="formRules.rejectNodeIdArr"
          >
            <el-select
              v-model="formData.rejectNodeIdArr"
              multiple
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in flowList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="允许转派给他人" prop="isReassignment">
            <el-checkbox
              v-model="formData.isReassignment"
              :true-label="1"
              :false-label="0"
            />
          </el-form-item>
        </div>
        <div class="notice-title" :style="{ color: sideTheme === 'theme-dark' ? '#fff' : '#333' }">通知设置</div>
        <el-form-item label="通知" prop="notify">
          <el-switch
            v-model="formData.notify"
            :active-value="true"
            :inactive-value="false"
            inactive-color
          />
        </el-form-item>
        <div v-if="formData.notify">
          <div style="margin-bottom: 10px">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="small"
              @click="addNotice"
            >添加</el-button>
          </div>
          <div
            v-for="(item, index) in formData.noticeList"
            :key="index"
            class="border"
          >
            <i
              class="el-icon-close"
              @click="formData.noticeList.splice(index, 1)"
            />
            <el-form-item label="设定条件" prop="conditionSwitch">
              <el-switch
                v-model="item.conditionsSwitch"
                :active-value="true"
                :inactive-value="false"
                inactive-color
              />
            </el-form-item>
            <div v-if="item.conditionsSwitch">
              <el-form-item prop="conditionMatch">
                <el-select v-model="item.conditionsMatch" placeholder="请选择">
                  <el-option label="满足任一条件" value="every" />
                  <el-option label="满足全部条件" value="all" />
                </el-select>
              </el-form-item>
              <el-form-item prop="conditions" style="display: flex;">
                <el-row :gutter="10">
                  <el-col :span="9">
                    <el-cascader
                      v-model="item.conditionsLabel"
                      clearable
                      size="small"
                      :options="computedCasOptions"
                      @change="conditionsValueChange($event, item)"
                    />
                  </el-col>
                  <el-col :span="5">
                    <el-select v-model="item.conditionsOption" placeholder="请选择">
                      <el-option
                        v-for="dict in conditionDict"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                        :disabled="dict.disabled"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="10">
                    <el-input v-if="item.componentsType == 'input' || item.componentsType == 'textarea' " v-model="item.conditionsValue" />
                    <el-radio-group v-if="item.componentsType == 'radio'" v-model="item.conditionsValue">
                      <el-radio v-for="opts in item.componentsOpts" :key="opts.value" :label="opts.value">{{ opts.label }}</el-radio>
                    </el-radio-group>
                    <el-input-number v-if="item.componentsType == 'number'" v-model="item.conditionsValue" />
                    <el-checkbox-group v-if="item.componentsType == 'checkbox'" v-model="item.conditionsValue">
                      <el-checkbox v-for="opts in item.componentsOpts" :key="opts.value" :label="opts.value">{{ opts.label }}</el-checkbox>
                    </el-checkbox-group>
                    <el-select v-if="item.componentsType == 'select'" v-model="item.conditionsValue" placeholder="请选择">
                      <el-option
                        v-for="dict in item.componentsOpts"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <el-time-picker
                      v-if="item.componentsType == 'time'"
                      v-model="item.conditionsValue"
                      :picker-options="{
                        selectableRange: '00:00:00 - 23:59:59'
                      }"
                      placeholder="选择时间"
                      :value-format="item.option? item.options.format : 'timestamp'"
                    />
                    <el-date-picker
                      v-if="item.componentsType == 'date'"
                      v-model="item.conditionsValue"
                      type="date"
                      placeholder="选择日期"
                      :value-format="item.option? item.options.format : 'timestamp'"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </div>

            <el-form-item label="通知方式" prop="noticeType">
              <el-select
                v-model="item.noticeType"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in noticeTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
            <div v-if="item.noticeType === 'mail'">
              <el-form-item label="通知对象" prop="userType">
                <el-checkbox-group v-model="item.userType">
                  <el-checkbox label="sendUser">发起人</el-checkbox>
                  <el-checkbox label="nextUser">下一节点处理人</el-checkbox>
                  <el-checkbox label="assignUser">指定用户</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item v-if="item.userType.includes('assignUser')" label="指定用户" prop="userArr">
                <el-select v-model="item.userArr" multiple clearable placeholder="请选择">
                  <el-option
                    v-for="dict in allUserList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                    :disabled="dict.disabled"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="通知标题" prop="mailTitleLabel">
                <el-input
                  v-model="item.mailTitleLabel"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  style="width: 200px"
                  clearable
                  @focus="
                    (val) => checkInput(item.mailTitleLabel, item, 'mailTitle')
                  "
                  @input="(val) => checkInput(val, item, 'mailTitle')"
                />

                <div class="fx">
                  <el-button
                    v-if="!item.mailTitleFxVisible"
                    type="primary"
                    plain
                    size="small"
                    @click="showFx(item, 'mailTitle')"
                  >fx</el-button>

                  <div v-else class="cascader_wrapper">
                    <div class="cascader_top">
                      <span>插入变量</span>

                      <i
                        class="el-icon-close"
                        @click="hiddenFx(item, 'mailTitle')"
                      />
                    </div>

                    <el-cascader-panel
                      v-model="item.mailTitleValue"
                      style="width: 100%"
                      clearable
                      size="small"
                      :props="casProps"
                      :options="casOptions"
                      @change="(val) => casClick(val, item, 'mailTitle')"
                    />
                  </div>
                </div>
              </el-form-item> -->
              <el-form-item label="通知内容" prop="mailContentLabel">
                <el-input
                  v-model="item.mailContentLabel"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  style="width: 200px"
                  clearable
                  maxlength="1000"
                  @focus="
                    (val) =>
                      checkInput(item.mailContentLabel, item, 'mailContent')
                  "
                  @input="(val) => checkInput(val, item, 'mailContent')"
                />

                <div class="fx">
                  <el-button
                    v-if="!item.mailContentFxVisible"
                    type="primary"
                    plain
                    size="small"
                    @click="showFx(item, 'mailContent')"
                  >fx</el-button>

                  <div v-else class="cascader_wrapper">
                    <div class="cascader_top">
                      <span>插入变量</span>

                      <i
                        class="el-icon-close"
                        @click="hiddenFx(item, 'mailContent')"
                      />
                    </div>

                    <el-cascader-panel
                      v-model="item.mailContentValue"
                      style="width: 100%"
                      clearable
                      size="small"
                      :props="casProps"
                      :options="casOptions"
                      @change="(val) => casClick(val, item, 'mailContent')"
                    />
                  </div>
                </div>
              </el-form-item>
            </div>
            <div v-else>
              <el-form-item label="URL">
                <el-input
                  v-model="item.restUrlLabel"
                  :style="item.requestType === 'GET'? 'width: 80%' : 'width: 100%;'"
                  clearable
                  @focus="
                    (val) =>
                      checkInput(item.restUrlLabel, item, 'restUrl')
                  "
                  @input="(val) => checkInput(val, item, 'restUrl')"
                >
                  <el-select slot="prepend" v-model="item.requestType" placeholder="请选择">
                    <el-option label="GET" value="GET" />
                    <el-option label="POST" value="POST" />
                    <el-option label="PUT" value="PUT" />
                  </el-select>
                </el-input>

                <div v-if="item.requestType === 'GET'" class="fx">
                  <el-button
                    v-if="!item.restUrlFxVisible"
                    type="primary"
                    plain
                    size="small"
                    @click="showFx(item, 'restUrl')"
                  >fx</el-button>

                  <div v-else class="cascader_wrapper">
                    <div class="cascader_top">
                      <span>插入变量</span>

                      <i
                        class="el-icon-close"
                        @click="hiddenFx(item, 'restUrl')"
                      />
                    </div>

                    <el-cascader-panel
                      v-model="item.restUrlValue"
                      style="width: 100%"
                      clearable
                      size="small"
                      :props="casProps"
                      :options="casOptions"
                      @change="(val) => casClick(val, item, 'restUrl')"
                    />
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="请求类型" prop="contentType">
                <el-select v-model="item.contentType" clearable>
                  <el-option
                    v-for="dict in contentTypeList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                    :disabled="dict.disabled"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="Headers" prop="headerList">
                <el-row v-for="(header, target) in item.headerList" :key="target" style="margin-bottom: 10px;">
                  <el-col :span="8">
                    <el-input v-model="header.key" placeholder="key" />
                  </el-col>
                  <el-col :span="11" style="padding: 0 10px;">
                    <el-input v-model="header.value" placeholder="value" />
                  </el-col>
                  <el-col :span="4" class="header-list-icons">
                    <i class="el-icon-circle-plus-outline" @click="handleHeaderList(item, target, 'add')" />
                    <i v-if="item.headerList.length >= 2 && item.headerList.length !== 1" class="el-icon-remove-outline" @click="handleHeaderList(item, target, 'minus')" />
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="Body" prop="bodyListLabel">
                <el-input
                  v-model="item.bodyListLabel"
                  :disabled="item.requestType == 'GET'"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  style="width: 200px"
                  clearable
                  @focus="
                    (val) =>
                      checkInput(item.bodyListLabel, item, 'bodyList')
                  "
                  @input="(val) => checkInput(val, item, 'bodyList')"
                />

                <div v-if="item.requestType !== 'GET'" class="fx">
                  <el-button
                    v-if="!item.bodyListFxVisible"
                    type="primary"
                    plain
                    size="small"
                    @click="showFx(item, 'bodyList')"
                  >fx</el-button>

                  <div v-else class="cascader_wrapper">
                    <div class="cascader_top">
                      <span>插入变量</span>

                      <i
                        class="el-icon-close"
                        @click="hiddenFx(item, 'bodyList')"
                      />
                    </div>

                    <el-cascader-panel
                      v-model="item.bodyListValue"
                      style="width: 100%"
                      clearable
                      size="small"
                      :props="casProps"
                      :options="casOptions"
                      @change="(val) => casClick(val, item, 'bodyList')"
                    />
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <condition-dialog ref="condition_dia" :flow-form="flowForm" @saveDia="saveDia" />
  </div>
</template>

<script>
import {
  getAllFormList,
  getAllRoleList,
  getAllUserList
} from '@/api/ticket/processDesign'
import { mapMutations, mapState } from 'vuex'
import {
  casClick,
  checkInput,
  flatten,
  flattenArr,
  hiddenFx,
  showFx,
  getFormComponent
} from '../utils/fx'
import conditionDialog from './conditionDialog.vue'
// import MyGenerateForm from '@/components/GenerateForm'
import { get } from '@/utils/request'
import { deepClone } from '@/utils'
const BASE_URL = window.baseUrl.ticket

export default {
  name: 'PropertyPanel',
  components: {
    conditionDialog
    // MyGenerateForm
  },
  props: {
    modeler: {
      type: Object,
      required: true
    },
    processId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showUserMore: false,
      // 表单可见性
      formVisibility: false,
      // 表单数据
      formData: {},
      // 是否不可编辑
      editable: true,
      // 选中的元素
      element: {},
      roles: [
        {
          value: 'manager',
          label: '经理'
        },
        {
          value: 'personnel',
          label: '人事'
        },
        {
          value: 'charge',
          label: '主管'
        }
      ],
      casOptions: [],
      casProps: { multiple: true },
      // 数字格式对象
      reverseObj: {},
      // 级联选择器关系数组
      relationArr: [],
      // 是否是网关接用户任务
      showFlowMore: false,
      expression: '',
      //  所有表单列表
      fromSystemList: [],
      //  分配方式
      actionModeList: [
        { value: 'preNodeAssign', label: '上个节点指定' },
        { value: 'autoAssign', label: '自动分配' }
      ],
      //  候选处理人
      peopleList: [
        { value: 'role', label: '角色' },
        { value: 'assignUser', label: '指定用户' },
        { value: 'allUser', label: '所有用户' }
      ],
      //  自动分配候选人: 宝蓝德还有部门
      autoPeopleList: [
        { value: 'role', label: '角色' },
        { value: 'assignUser', label: '指定用户' }
      ],
      //  所有角色列表
      allRoleList: [],
      //  指定用户列表
      allUserList: [],
      //  删除节点
      deleteNode: false,
      //  可驳回节点
      flowArr: [],
      flowList: [],
      //  前置节点是否为互斥节点
      isGateway: false,
      //  当前节点的前置节点所选表单
      flowForm: [],
      //  通知方式
      noticeTypeList: [
        { value: 'rest', label: 'Restful API' },
        // { value: 'mail', label: '邮件通知' }
        { value: 'mail', label: '站内信' }
      ],
      //  请求类型
      contentTypeList: [
        { value: 'application/json', label: 'application/json' },
        { value: 'application/xml', label: 'application/xml' },
        { value: 'text/plain', label: 'text/plain' },
        { value: 'multipart/form-data', label: 'multipart/form-data' },
        { value: 'application/x-www-form-urlencoded', label: 'application/x-www-form-urlencoded' }
      ],
      //  选中表单模板
      formTemplate: null,
      // 条件等式
      conditionDict: [{
        'label': '等于',
        'value': '=='
      }, {
        'label': '不等于',
        'value': '!='
      }, {
        'label': '小于',
        'value': '<'
      }, {
        'label': '大于',
        'value': '>'
      }, {
        'label': '小于等于',
        'value': '<='
      }, {
        'label': '大于等于',
        'value': '>='
      }],
      //  表单必填项校验：主表单
      formRules: {
        nodeName: [{ required: true, message: '请输入步骤名称', trigger: ['blur', 'change', 'input'] }],
        expression: [{ required: true, message: '请配置跳转条件', trigger: ['blur', 'change', 'input'] }],
        formId: [{ required: true, message: '请为步骤节点配置表单', trigger: 'change' }],
        candidateMode: [{ required: true, message: '请选择处理人类型', trigger: 'change' }],
        candidateUserArr: [{ required: true, message: '请选择处理人', trigger: 'change' }],
        nodeAssignMode: [{ required: true, message: '请选择分配方式', trigger: 'change' }],
        signUserArr: [{ required: true, message: '请选择处理人', trigger: 'change' }],
        rejectNodeIdArr: [{ required: true, message: '请选择驳回步骤', trigger: 'change' }]
      },
      //  当前页面表单验证是否通过
      formValidFlag: true,
      //  级联选默认字段
      defaultCasOptions: [
        {
          value: 'normal',
          label: '默认',
          children: [
            {
              value: 'promoter',
              label: '发起人'
            },
            {
              value: 'createtime',
              label: '创建时间'
            },
            {
              value: 'title',
              label: '标题'
            },
            {
              value: 'serialNum',
              label: '流水号'
            },
            {
              value: 'team',
              label: '团队'
            },
            {
              value: 'organization',
              label: '组织'
            }
          ]
        }
      ]
    }
  },
  computed: {
    propertyStyle() {
      const width = !this.userTask
        ? '300px'
        : this.formData.notify && this.formData.noticeList?.length
          ? '700px'
          : '300px'
      return { width }
    },
    // 开始事件
    startEvent() {
      if (!this.element) {
        return
      }
      return this.element.type === 'bpmn:StartEvent'
    },
    endEvent() {
      if (!this.element) {
        return
      }
      return this.element.type === 'bpmn:EndEvent'
    },
    // 互斥网关事件
    exclusiveGateway() {
      if (!this.element) {
        return
      }

      return this.element.type === 'bpmn:ExclusiveGateway'
    },
    // 平行网关
    parallelGateway() {
      if (!this.element) {
        return
      }
      return this.element.type === 'bpmn:ParallelGateway'
    },
    // 任务事件
    userTask() {
      if (!this.element) {
        return
      }
      return this.element.type === 'bpmn:UserTask'
    },
    // 连线
    sequenceFlow() {
      if (!this.element) {
        return
      }
      return this.element.type === 'bpmn:SequenceFlow'
    },
    //  候选人字典
    computedPopleList() {
      let _list = []
      if (this.formData.nodeAssignMode === 'preNodeAssign') {
        _list = this.peopleList
      } else {
        _list = this.autoPeopleList
      }
      return _list
    },
    //  用户字典
    computedPeople() {
      let _list = []
      if (this.formData.candidateMode === 'role') {
        _list = this.allRoleList
      } else if (this.formData.candidateMode === 'assignUser') {
        _list = this.allUserList
      }
      return _list
    },
    //  条件级联选择
    computedCasOptions() {
      const _list = []
      if (this.casOptions.length > 1) {
        this.casOptions.forEach((i, index) => {
          if (index !== 0) {
            const x = deepClone(i)
            if (x.children && x.children.length > 0) {
              x.children = x.children.filter(o => o.value !== 'allData')
            }
            _list.push(x)
          }
        })
      }
      return _list
    },
    ...mapState({
      // 节点表单信息
      nodeInfo: (state) => state.bpmn.nodeInfo,
      // 节点连线信息
      condition: (state) => state.bpmn.condition,
      //  获取当前系统主题
      sideTheme: (state) => state.settings.sideTheme
    })
  },
  watch: {
    formVisibility: {
      async handler(newValue, oldValue) {
        if (newValue) {
          //  每次打开都走一遍字典接口
          await this.getDict()
          await this.getAllForm()
          //  设置本条数据的必填项
          // console.log(this.flowArr.flow, '>>> this.flowArr.flow')
          if (this.flowArr.flow && this.flowArr.flow[0].includes('Gateway')) {
            // this.isGateway = true
            // this.formData.nodeAssignMode = 'autoAssign'
          } else {
            // this.isGateway = false
          }
          //  跳转条件回显
          this.dealExpression()
          for (const i in this.nodeInfo) {
            if (!this.nodeInfo[i].formId) { continue }
            if (this.flowArr.flow?.includes(i)) {
              //  将前置节点选中的表单从表单中剔除
              // this.fromSystemList = this.fromSystemList.filter(item => item.id !== this.nodeInfo[i].formId)
              // this.bindFormData()
              //  生成跳转条件所需数据
              /*  const _flowForm = this.fromSystemList.filter(item => item.id === this.nodeInfo[i].formId)
              _flowForm && _flowForm.forEach(item => {
                const _formTemplate = JSON.parse(item.formTemplate) || []
                const _children = []
                this.flowForm = []
                _formTemplate.list && _formTemplate.list.forEach(item => {
                  if (item.type === 'grid') {
                    item.columns.forEach(j => {
                      j.list.forEach(k => {
                        _children.push({
                          value: k.model,
                          label: k.name,
                          type: k.type,
                          options: k?.options
                        })
                      })
                    })
                  } else {
                    _children.push({
                      value: item.model,
                      label: item.name,
                      type: item.type,
                      options: item?.options
                    })
                  }
                })
                this.flowForm.push({
                  value: item.id,
                  label: item.label,
                  children: _children
                })
              }) */
            }
          }
        }
        if (!newValue) {
          const id = this.formData.id
          //  关闭时验证
          this.handleValidate()
          //  关闭时清空前置表单
          this.flowForm = []
          if (this.sequenceFlow && this.showFlowMore) {
            this.changeCondition({ [id]: this.formData })
          } else if (this.userTask || this.exclusiveGateway) {
            this.changeNodeInfo({ [id]: this.formData })
          }
        }
      }
    },
    'flowArr.flow': {
      handler(val) {
        if (val) {
          //  根据前置节点设置数据
          this.flowList = []
          for (const i in this.nodeInfo) {
            //  将开始节点剔除后生成可驳回步骤列表
            if (this.flowArr.flow?.includes(i) && i.includes('Activity_')) {
              this.flowList.push({
                id: this.nodeInfo[i].id,
                label: this.nodeInfo[i].nodeName || this.nodeInfo[i].id
              })
            }
          }
        }
      },
      deep: true
    },
    'formData.nodeAssignMode': {
      handler(val) {
        /*  if (val === 'preNodeAssign') {
          this.formData.candidateMode = 'allUser'
        } else {
          this.formData.candidateMode = 'role'
        } */
      }
    },
    'formData.formId': {
      handler(val) {
        if (val) {
          if (!this.$route.query.type) {
            this.setDefaultNotice()
          }
          this.bindFormData(val)
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.handleModeler()
    this.reverseObj = flatten(this.casOptions, 'y')
    flattenArr(this.casOptions, [], this.relationArr)
  },
  methods: {
    ...mapMutations({
      getNodeInfo: 'bpmn/getNodeInfo',
      changeNodeInfo: 'bpmn/changeNodeInfo',
      changeCondition: 'bpmn/changeCondition'
    }),
    handleModeler() {
      // 监听节点选择变化
      this.modeler.on('selection.changed', (e) => {
        const element = e.newSelection[0]
        // 是否要隐藏表单
        if (!element) {
          this.formVisibility = false
        } else {
          this.element = element
        }
      })
    },
    // 属性面板名称，更新回流程节点
    nameChange(name) {
      const modeling = this.modeler.get('modeling')
      modeling.updateLabel(this.element, name)
    },
    // 打开连线对话框
    addCondition() {
      const { conditions, setCondition = 'all', selectedRow } = this.formData
      this.$refs.condition_dia.formData = {
        conditions: JSON.parse(JSON.stringify(conditions)),
        setCondition: JSON.parse(JSON.stringify(setCondition)),
        selectedRow: JSON.parse(JSON.stringify(selectedRow))
      }
      this.$refs.condition_dia.show()
    },
    // 增加通知
    addNotice() {
      this.formData.noticeList.push({
        noticeType: 'mail', // 通知类型
        userType: [], // 通知对象
        mailTitleFxVisible: false, //  通知标题相关
        mailTitleValue: [],
        mailTitleLabel: '',
        mailContentFxVisible: false, //  通知内容相关
        mailContentValue: [],
        mailContentLabel: '',
        conditionsSwitch: true, //  设定条件
        conditionsMatch: 'all',
        conditions: {},
        conditionsLabel: [], //  选择表单后的条件项
        conditionsOption: '', // 等于、不等于...
        conditionsValue: '', //  表单后的条件项的对应值
        componentsType: 'input', // 表单条件项type
        componentsOpts: '', // 表单条件项options
        requestType: 'GET', //  接口类型
        restUrlFxVisible: false, //  请求URL相关
        restUrlValue: [],
        restUrlLabel: '',
        contentType: '', //  请求类型
        headerList: [
          { 'key': '', 'value': '' }
        ], //  请求头
        bodyListFxVisible: false, //  请求体相关
        bodyListValue: [],
        bodyListLabel: ''
      })
    },
    async saveDia(data) {
      this.formData.conditions = data.conditions
      this.formData.setCondition = data.setCondition
      this.formData.selectedRow = data.selectedRow
      await this.dealExpression()
      this.changeCondition({ [this.formData.id]: this.formData })
      this.$emit('update', this.formData, 'sequenceFlow', this.expression)
    },
    async dealExpression() {
      let str = ''
      let _str = ''
      if (this.formData.conditions?.length) {
        str += '${'
        this.formData.conditions.forEach((item, index) => {
          if (index === this.formData.conditions.length - 1) {
            str += `${item.variable}${item.conditionalOpt}${item.conditionalVal}`
            _str += `${item.variable[1]}${item.conditionalOpt}${item.conditionalVal}`
          } else {
            const Connector = item.setCondition == 'all' ? '&&' : '||'
            str += `${item.variable}${item.conditionalOpt}${item.conditionalVal}${Connector}`
            _str += `${item.variable[1]}${item.conditionalOpt}${item.conditionalVal}${Connector}`
          }
        })
        str += '}'
      }
      this.expression = _str
      this.$set(this.formData, 'expression', str)
      this.$refs.formRef && this.$refs.formRef.validateField('expression')
      this.handleValidate()
    },
    // 显示fx
    showFx(item, attr) {
      showFx(item, attr, this.relationArr, this.reverseObj)
    },
    // 隐藏fx
    hiddenFx(item, attr) {
      hiddenFx(item, attr)
    },
    // 输入框的方法
    checkInput(val, Obj, attr) {
      // console.log(val);
      checkInput(val, Obj, attr, this.relationArr, this.reverseObj)
    },
    // 级联选择器选中事件
    casClick(val, Obj, attr) {
      casClick(val, Obj, attr, this.relationArr, this.reverseObj)
    },
    /** 获取相关字典 */
    async getDict() {
      await this.getAllForm()
      await this.getAllRole()
      await this.getAllUser()
      await this.dealExpression()

      // 判断nodeInfo是否需要重置
      if (!this.formData.notify) {
        this.setDefaultNotice()
      }
    },
    /** 获取所有表单 */
    getAllForm() {
      getAllFormList().then((res) => {
        this.fromSystemList = res.map((item) => {
          return { value: item.id, label: item.name, ...item }
        })
        /**
       * 设置级联选
       * params formId  当前元素的节点表单Id
       */
        if (this.formData.formId) {
          this.bindFormData(this.formData.formId)
        } else {
          this.bindFormData()
        }
      })
    },
    /** 获取所有角色 */
    getAllRole() {
      getAllRoleList().then((res) => {
        this.allRoleList = res.map((item) => {
          return { value: item.id, label: item.name }
        })
      })
    },
    /** 获取所有用户 */
    getAllUser() {
      getAllUserList().then((res) => {
        this.allUserList = res.map((item) => {
          return { value: item.id, label: item.name }
        })
      })
    },
    /** 更新json2xml */
    bindFormData(currentId) {
      const _form = this.fromSystemList.find(
        (item) => item.id === currentId
      )
      const _formTemplate = _form?.formTemplate
      this.formTemplate = _formTemplate && JSON.parse(_formTemplate).list.map((item) => {
        return {
          id: item.model,
          label: item.name,
          type:
            item.type === 'time' || item.type === 'date' ? 'date' : 'string',
          key: item.key,
          component: item.type,
          options: item.options?.options,
          list: item.type === 'grid'
            ? item.columns
            : []
          // generateForm: item
        }
      })
      /*
      //  如果表单选中，为级联选择器添加相关表单模板
      if (currentId) {
        const _children = []
        this.formTemplate.forEach(item => {
          if (item.component === 'grid') {
            item.list.forEach(j => {
              j.list.forEach(k => {
                _children.push({
                  value: k.model,
                  label: k.name,
                  type: k.type,
                  options: k.options
                  // generateForm: k
                })
              })
            })
          } else {
            _children.push({
              value: item.id,
              label: item.label,
              type: item.component,
              options: item.options
              // generateForm: item
            })
          }
        })
        console.log('级联选的数据---', _children)
        this.casOptions = this.defaultCasOptions
        this.casOptions.push({
          value: _form.id,
          label: _form.label,
          children: _children
        })
        // 添加后重新扁平化fx所需数据
        this.reverseObj = flatten(this.casOptions, 'y')
        flattenArr(this.casOptions, [], this.relationArr)
      } */
      // 筛选出元素节点有formId
      const _this = this
      this.casOptions = JSON.parse(JSON.stringify(this.defaultCasOptions))
      this.flowForm = []
      const formsid = []
      // 获取元素元素选中的表单
      const selectedForms = []
      // const nodeKeys = Object.keys(this.nodeInfo)
      this.flowArr.flow && this.flowArr.flow.length && this.flowArr.flow.forEach(i => {
        if (i.includes('Activity_') && this.nodeInfo[i].formId) {
          formsid.push(this.nodeInfo[i].formId)
        }
      })
      if (currentId) {
        formsid.push(currentId)
      }
      //  将数组去重
      const uniqueFormsid = Array.from(new Set(formsid))
      uniqueFormsid.forEach(j => {
        //  筛选所有表单中相同的id
        const sameFormIds = _this.fromSystemList.filter(list => {
          return list.id == j
        })
        sameFormIds.length > 0 && selectedForms.push(...sameFormIds)
      })
      selectedForms.length > 0 && selectedForms.forEach(i => {
        const lists = JSON.parse(i?.formTemplate).list
        const formLists = getFormComponent(lists)
        this.casOptions.push(
          {
            label: i.name,
            value: i.value,
            children: [{
              label: '全部数据',
              value: 'allData'
            }, ...formLists]
          }
        )
        this.flowForm.push({
          label: i.name,
          value: i.value,
          children: formLists
        })
      })
      // 添加后重新扁平化fx所需数据
      this.reverseObj = flatten(this.casOptions, 'y')
      flattenArr(this.casOptions, [], this.relationArr)
      if (currentId && this.formTemplate) {
        this.$emit('update', this.formData, 'userTask', this.formTemplate)
      }
    },
    /** 设置默认值 */
    setDefaultNotice() {
      this.formData.noticeList && this.formData.noticeList.forEach(item => {
        item.conditionsLabel = []
        item.conditionsOption = ''
        item.conditionsValue = null
        item.componentsOpts = []
        item.componentsType = 'input'
      })
      this.casOptions = JSON.parse(JSON.stringify(this.defaultCasOptions))
    },
    /** 条件级联变化 */
    async conditionsValueChange(val, item) {
      item.conditionsValue = ''
      const selectedOption = this.casOptions.filter(i => {
        return i.value == val[0]
      })
      const _type = selectedOption[0].children.filter(i => {
        return i.value == val[1]
      })[0].type
      const _options = selectedOption[0].children.filter(i => {
        return i.value == val[1]
      })[0].options.options
      const _list4 = [{
        'label': '等于',
        'value': '=='
      }, {
        'label': '不等于',
        'value': '!='
      }, {
        'label': '包含',
        'value': 'contain'
      }, {
        'label': '不包含',
        'value': 'exclusive'
      }]
      const _list6 = [{
        'label': '等于',
        'value': '=='
      }, {
        'label': '不等于',
        'value': '!='
      }, {
        'label': '小于',
        'value': '<'
      }, {
        'label': '大于',
        'value': '>'
      }, {
        'label': '小于等于',
        'value': '<='
      }, {
        'label': '大于等于',
        'value': '>='
      }]
      const _type4 = ['input', 'textarea', 'radio', 'checkbox', 'select']
      if (_type4.includes(_type)) {
        this.conditionDict = _list4
      } else {
        this.conditionDict = _list6
      }
      item.componentsType = _type
      if (_options && _options.remote) {
        const reg = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g
        const reg2 = /^\//g
        if (reg.test(_options.remoteFunc)) {
          get(_options.remoteFunc).then(res => {
            item.componentsOpts = res.map(item => {
              return {
                value: item[_options.props.value],
                label: item[_options.props.label]
              }
            })
          })
        } else if (reg2.test(_options.remoteFunc)) {
          get(BASE_URL + _options.remoteFunc).then(res => {
            item.componentsOpts = res.map(item => {
              return {
                value: item[_options.props.value],
                label: item[_options.props.label]
              }
            })
          })
        }
      } else {
        item.componentsOpts = _options
      }
    },
    /** 请求头 */
    handleHeaderList(item, target, type) {
      if (type === 'add') {
        item.headerList.splice(target, 0, { 'key': '', 'value': '' })
      } else {
        item.headerList.splice(target, 1)
      }
    },
    /** 校验 */
    handleValidate() {
      //  新增节点后可能拿不到id、预览和流程跳转过来就不再校验
      if (!this.formData.id || this.$route.query.type === 'view') return
      //  当节点类型为 用户任务 和 互斥连线时，进行必填校验
      // console.log('进入校验------', this.formData.id)
      if (this.formData.id.includes('Activity') || this.formData.id.includes('Flow')) {
        if (this.$refs.formRef) {
          this.$refs.formRef.validate((valid) => {
            if (!valid) {
              // this.$message.error('请检查必填项')
              this.formData.formValidFlag = false
              this.$emit('set-error', [this.formData.id])
            } else {
              this.formData.formValidFlag = true
              this.$emit('set-default', this.formData.id)
            }
          })
        }
      } else {
        //  当节点类型为 互斥网关 时，走进这个判断
        this.formData.formValidFlag = true
        this.$emit('set-default', this.formData.id)
      }
    },
    //  表单元素发生变化
    handleGenerateChage(field = '', value = '', data = {}) {
      // this.formInstances[this.formInstances.length - 1].formData = JSON.stringify(data)
      // console.log(data)
    },
    // 处理人类型改变
    handleChangeUserType(val) {
      this.$set(this.formData, 'candidateUserArr', [])
    },
    //  节点表单变化
    async handleChangeFormId(val) {
      this.formData.noticeList.length > 0 && this.formData.noticeList.forEach((i, index) => {
        this.formData.noticeList[index].mailContentLabel = ''
        this.formData.noticeList[index].mailContentValue = []
        this.formData.noticeList[index].mailContent = ''
      })
      await this.changeNodeInfo({ [this.formData.nodeId]: this.formData })
      this.bindFormData(this.formData.nodeId)
    }
  }
}
</script>

<style lang="scss" scoped>
.property-panel {
  position: absolute;
  z-index: 100;
  right: 0px;
  top: 0px;
  border-left: 1px solid #cccccc;
  padding: 20px;
  height: 100%;
  background: #fff;
  overflow: auto;
}
// 边框样式
.border {
  border-bottom: 1px dashed #cecece;
  border-top: 1px dashed #cecece;
  padding: 20px 0 10px 0;
  position: relative;
  & + .border {
    border-top: none;
  }
  & > i.el-icon-close {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}
.notice-title {
  margin-bottom: 15px;
  font-size: 18px;
  font-weight: 600;
}
.inline-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .el-select,
  .el-input {
    margin-right: 10px;
  }
  .el-icon-circle-plus {
    color: #4b6eef;
  }
  i + i {
    margin-left: 5px;
  }
}
.el-select {
  width: 100%;
}
.fx {
  display: inline-block;
  position: relative;
  margin-left: 10px;
  height: 100%;
  .cascader_wrapper {
    position: absolute;
    z-index: 100;
    top: -100px;
    min-width: 180px;
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    .cascader_top {
      width: 100%;
      padding: 2px 10px;
      background: #f6f6f6;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
::v-deep {
  .el-cascader-menu__list {
    background: #fff;
  }
  .el-input-group__append,
  .el-input-group__prepend {
    background-color: transparent;
    padding: 0;
    width: 100px;
  }
  .el-input-group__prepend .el-select {
    margin: 0;
  }
}

//  请求头操作栏
.header-list-icons {
  font-size: 18px;

  i {
    margin-right: 5px;
    cursor: pointer;
  }
}
</style>
